
const { ccclass, property } = cc._decorator;

import { NetLauncher } from "./NetLauncher";
import { ModuleLauncher } from "./ModuleLauncher";
import { Manager } from "../manager/Manager";
import { UILanuncher } from "./UILauncher";
import { SdkLauncher } from "./SdkLauncher";
import { Cfg } from "../config/Cfg";
import { Notifier } from "../framework/Notifier";
import { Time } from "../framework/Time";
import { ListenID } from "../ListenID";
import { GameVoManager } from "../manager/GameVoManager";
import { Util } from "../utils/Util";
import NetAdapter from "../adpapter/NetAdapter";
import { AlertManager, AlertType } from "../alert/AlertManager";
import LoginManager from "../manager/LoginManager";
import GlobalData from "../GlobalData";
import DouyinManager from "../manager/DouyinManager";
import KuaishouManager from "../manager/KuaishouManager";
import AdManager from "../manager/AdManadgr";
import CaptureUtils from "../utils/Capture";
import DeviceManager from "../manager/DeviceManager";
import { TestUserInfo, UseTestUserInfo } from "../TestUserInfo";
import { Const } from "../config/Const";
import HotupdateManager from "../manager/HotupdateManager";

@ccclass
export default class Launcher extends cc.Component {
  @property(cc.ProgressBar)
  public progress: cc.ProgressBar = null;

  @property(cc.Label)
  public text: cc.Label = null;

  @property(cc.Label)
  public progressText: cc.Label = null;

  @property(cc.Label)
  public version: cc.Label = null;


  @property(cc.Node)
  public btnWeixinLogin: cc.Node = null;


  @property(cc.Node)
  public canvasNode: cc.Node = null;

  @property(cc.Node)
  public appleLogin_view: cc.Node = null;

  @property(cc.Node)
  login_view: cc.Node = null;

  @property(cc.EditBox)
  login_name: cc.EditBox = null;

  @property(cc.EditBox)
  login_password: cc.EditBox = null;

  @property(cc.Node)
  register_view: cc.Node = null;

  @property(cc.EditBox)
  register_name: cc.EditBox = null;

  @property(cc.EditBox)
  register_password: cc.EditBox = null;

  @property(cc.EditBox)
  register_password_1: cc.EditBox = null;

  @property(cc.Node)
  Copyright_Owner: cc.Node = null;

  agent_uid = "0";
  _login: boolean = false;

  onLoad() {
    console.log("Launcher onLoad");
    cc.game.addPersistRootNode(this.node);

    // if (CC_DEBUG) {

    //     GlobalData.inst.showCheat = true;
    //     GlobalData.inst.tempHide = true;
    // }

    this.hideAllLoginBtn();
  }

  start() {
    console.log("launcher start");
    this.version.string = "ver:" + GlobalData.inst.version;
    console.log(GlobalData.inst.version);
    let canvas = cc.director.getScene().children[1];
    let node = canvas.getChildByName("bg");
    this.isStartLoad = false;
    new UILanuncher();
    this.startLogin();
  }


  login(event: cc.Event.EventTouch, customdata: string) {

     //QQ互联
    //  this.loginKuaishou();
    //  return;
    //本地测试账号注册登录
    // if (CC_DEBUG) {
      this.appleLogin();
    //   return;
    // }
  }

  appleLogin() {
    if (CC_DEBUG) {
      this.login_name.string ="test0005"
      this.login_password.string ="123456a"
    }
    do {
      if (this.login_name.string == "" || this.login_password.string == "") {
        AlertManager.showNormalTips("请输入用户名和密码");
        break;
      }
      if (this.login_name.string.length < 6) {
        AlertManager.showNormalTips("用户名不能小于6位");
        break;
      }
      if (this.login_password.string.length < 6) {
        AlertManager.showNormalTips("密码不能小于6位");
        break;
      } else {
        NetAdapter.appleLogin({
          user_login: this.login_name.string,
          user_pass: this.login_password.string,
        })
          .then((res) => {
            console.log("appleLogin res", res);
            let data = this.getUserInfo(res);
            console.log("appleLogin", data);
            if (data) {
              Util.logExt(res, "登录成功！");
              AlertManager.showNormalTips("登录成功！");
              this.appleLogin_view.active = false;
              this.parsedLoginData(data);
              this.showLoading();
            }
          })
          .catch((err) => {
            console.log(err);
            // AlertManager.showNormalTips(err.msg)
          });
        break;
      }
    } while (false);
  }

  // 苹果注册按钮事件
  appleRegister() {
    do {
      if (this.register_name.string.length <= 0) {
        AlertManager.showNormalTips("请输入用户名");
        break;
      }
      if (this.register_name.string.length < 6) {
        AlertManager.showNormalTips("用户名长度不能小于6位");
      }
      if (this.register_password.string.length <= 0) {
        AlertManager.showNormalTips("请输入密码");
        break;
      }
      if (this.register_password.string.length < 6) {
        AlertManager.showNormalTips("密码长度不能小于6位");
        break;
      }
      if (this.register_password.string != this.register_password_1.string) {
        AlertManager.showNormalTips("两次密码不一致");
        break;
      } else {
        NetAdapter.appleResRegister({
          user_login: this.register_name.string,
          user_pass: this.register_password.string,
          // user_pass2: this.register_password_1.string,
        })
          .then((res) => {
            // AlertManager.showNormalTips("注册成功")
            Util.logExt(res, "注册成功");
            // AlertManager.showNormalTips(res.msg)
            // let data = this.getUserInfo(res);

            console.log(res);
            AlertManager.showNormalTips("注册成功!");
            this.showAppleRegister();
          })
          .catch((err) => {
            console.log("appleResErr", err);
            // AlertManager.showNormalTips(err.msg)
          });
        break;
      }
    } while (false);
  }

  public isLogin: boolean = true;
  // 注册界面和登录界面互相转化
  public showAppleRegister() {
    this.isLogin = this.login_view.active;
    if (this.isLogin) {
      this.login_view.active = false;
      this.register_view.active = true;
    } else {
      this.login_view.active = true;
      this.register_view.active = false;
    }
  }

  ensureImageExtension(url) {
    // Regular expression to check if URL ends with .jpg or .png
    const imageExtensionPattern = /\.(jpg|png)$/i;

    // Test if the URL ends with .jpg or .png
    if (!imageExtensionPattern.test(url)) {
      // If not, add .png to the end of the URL
      return url + "?image=.png";
    }

    // If it already ends with .jpg or .png, return the URL as is
    return url;
  }

  parsedLoginData(data: any) {
    GlobalData.inst.notice_title = data.notice_title;
    GlobalData.inst.notice_desc = data.notice_desc;
    GlobalData.inst.token = data.token;
    GlobalData.inst.id_card_no = data.id_card_no || "";
    GlobalData.inst.user_name = data.user_name || "";
    GlobalData.inst.user_certverify_preconsult =
      data.user_certverify_preconsult || 0;
    GlobalData.inst.real_name_authentication =
      data.real_name_authentication || 0;
    GlobalData.inst.zfbAuthentication = data.zfbAuthentication || 0;
    GlobalData.inst.uid = data.id;
    GlobalData.inst.user_nickname = data.user_nickname;
    GlobalData.inst.userinfo = data.dataGame || {};
    GlobalData.inst.create_time = data.create_time;
    console.log(
      "parsedLoginData",
      GlobalData.inst.real_name_authentication,
      data.real_name_authentication
    );
    if (GlobalData.inst.uid && !GlobalData.inst.tempHide) {
      cc.sys.localStorage.setItem(Const.LOGIN_UID, GlobalData.inst.uid);
      console.log("uid", GlobalData.inst.uid);
    }
    if (GlobalData.inst.token && !GlobalData.inst.tempHide) {
      cc.sys.localStorage.setItem(Const.LOGIN_TOKEN, GlobalData.inst.token);
    }
    if (data.user_login) {
      cc.sys.localStorage.setItem(Const.LOGIN_OPENID, data.user_login);
    }
    if (UseTestUserInfo) {
      GlobalData.inst.userinfo = TestUserInfo;
    }
    GlobalData.inst.diamond = data.diamond;
    GlobalData.inst.coin = data.coin;
    GlobalData.inst.agent_uid = data.agent_uid;
    GlobalData.inst.diffbattle = Number(data.diffbattle);

    let userData = GameVoManager.getInstance.myUserVo;
    userData.nick_name = GlobalData.inst.user_nickname;
    userData.avatar_url = this.ensureImageExtension(data.avatar);
    console.log("userData.avatar_url", userData.avatar_url);
    GlobalData.inst.userinfo.avatar_url = userData.avatar_url;
    GlobalData.inst.userinfo.nick_name = userData.nick_name;
    GlobalData.inst.provincecode = data.provincecode || 0;
    // Manager.storage.setString("localUserVo", JSON.stringify(GlobalData.inst.userinfo));
    AdManager.inst.preLoadReward();
    AdManager.inst.preLoadInterstitial();
  }

  private loginKuaishou() {
    // let options = ks.getLaunchOptionsSync();
    // console.log("KS login getLaunchOptionsSync", options);
    // console.log("KS login getLaunchOptionsSync options.query", options.query);
    let alias = 0;
    // if (options.query && options.query.uid) {
    //   alias = parseInt(options.query.uid);
    // }
    
    KuaishouManager.inst.login((login) => {
      console.log("KuaishouManager login", login);
      let userinfo = login.userInfo || {};
      let senddata : any = {
        code: login.login.code,
        avatarUrl: userinfo.avatarUrl || "https://jyxb-server.ruishangkeji.cn/logo.png",
        nickName: userinfo.nickName || "快手用户",
      };
      if (alias > 0) {
        senddata.alias = alias;
      }

      console.log("向服务器发送登录请求数据", senddata);
      NetAdapter.loginKuaiShou(senddata).then(
        (loginKuaiShouRes) => {
          let data = this.getUserInfo(loginKuaiShouRes);
          this.hideAllLoginBtn();
          this.parsedLoginData(data);
          this.showLoading();
        }
      );
    });
  }
  //快手小游戏自动登录
  private loginKuaishouByopenid(openid) {
    // let options = ks.getLaunchOptionsSync();
    // console.log("KS login getLaunchOptionsSync", options);
    // console.log("KS login getLaunchOptionsSync options.query", options.query);
    let alias = 0;
    // if (options.query && options.query.uid) {
    //   alias = parseInt(options.query.uid);
    // }

    let senddata : any = {
      open_id: openid,
    };
    if (alias > 0) {
      senddata.alias = alias;
    }

    console.log("向服务器发送登录请求数据", senddata);
    NetAdapter.loginKuaiShou(senddata).then(
      (loginKuaiShouRes) => {
        let data = this.getUserInfo(loginKuaiShouRes);
        this.hideAllLoginBtn();
        this.parsedLoginData(data);
        this.showLoading();
      }
    );
  }

  getUserInfo(res: any) {
    let data = res;
    if (!data || Object.keys(data).length == 0) {
      Util.logExt({}, "info[0]为空");
      return;
    }
    return data;
  }

  showLoading() {
    this.progress.node.active = true;
    this.text.node.active = this.progress.node.active;
    this.scheduleOnce(() => {
      this.loadConfig();
    }, 1);
  }

  private count: number = 0;
  private downtime: number = 0.5;
  private isStartLoad: boolean = false;
  moveon() {
    try {
      if (this.text) {
        this.count %= 6;
        this.text.string = this.getString(".", this.count);
        ++this.count;
        this.downtime = 0.5;
      } else {
        this.downtime = 99999;
      }
    } catch (error) {
      this.downtime = 999999;
    }
  }

  hideAllLoginBtn() {
    this.btnWeixinLogin.active = false;
    this.appleLogin_view.active = false;
  }

  showLoginBtn() {
      this.btnWeixinLogin.active = true;
      //本地测试账号注册登录
      // if (CC_DEBUG) {
        this.appleLogin_view.active = true;
      // }
  }
  startLogin() {
    this.showLoginBtn();

    this.isStartLoad = true;

    let logined = cc.sys.localStorage.getItem("logined") || "0";
    let account = cc.sys.localStorage.getItem("account") || "未知用户名";
    let login_type = cc.sys.localStorage.getItem("login_type");

    Util.logExt({ logined }, "登录状态");

    let loginuid = cc.sys.localStorage.getItem(Const.LOGIN_UID) || "";
    let logintoken = cc.sys.localStorage.getItem(Const.LOGIN_TOKEN) || "";
    Util.logExt({ loginuid, logintoken }, "LOGIN_AUTO");
    if (loginuid && logintoken) {
      // this.hideAllLoginBtn();
      //快手小游戏
      let login_openid = cc.sys.localStorage.getItem(Const.LOGIN_OPENID) || "";
      console.log("快手小游戏，每次都需要走登录",login_openid);
      if(login_openid)
      {
        this.loginKuaishouByopenid(login_openid);
      }else
      {
        this.loginKuaishou();
      }
      return;
    }

    this.progress.node.active = false;
    this.text.node.active = this.progress.node.active;
  }
  getString(str, count) {
    let newstr = "加载中";
    let a = str;
    for (let i = 0; i < count; i++) {
      a += str;
    }
    newstr += a;
    return newstr;
  }

  update(dt: number) {
    Time.update(dt);
    Manager.loader.Update(dt);
    // this._net.Update(dt);
    if (this.isStartLoad) {
      this.downtime -= dt;
      if (this.downtime <= 0) {
        this.moveon();
      }
    }
  }

  onStartGame(event) {
    event.target.getComponent(cc.Animation).stop();
    Notifier.send(ListenID.Login_Finish);
  }

  //加载配置
  async loadConfig() {
    this.progress.progress = 0;
    GameVoManager.getInstance.myUserVo.loadState = 0;
    GameVoManager.getInstance.stateVo.loadTime = new Date().valueOf();
    GameVoManager.getInstance.myUserVo.loadState = 1;
    await Promise.all([
      Cfg.initLocalJson("Barrier", this.progressText, this.progress),
      Cfg.initLocalJson("Drop", this.progressText, this.progress),
      Cfg.initLocalJson("Monster", this.progressText, this.progress),
      Cfg.initLocalJson("Weapon", this.progressText, this.progress),
      Cfg.initLocalJson("Dial", this.progressText, this.progress),
      Cfg.initLocalJson("Boss", this.progressText, this.progress),
      Cfg.initLocalJson("Intensify", this.progressText, this.progress),
      Cfg.initLocalJson("DropPool", this.progressText, this.progress),
      Cfg.initLocalJson("DropPreview", this.progressText, this.progress),
      Cfg.initLocalJson("EquipUnlock", this.progressText, this.progress),
      Cfg.initLocalJson("Store", this.progressText, this.progress),
      Cfg.initLocalJson("Equip", this.progressText, this.progress),
      Cfg.initLocalJson("Surprise", this.progressText, this.progress),
      Cfg.initLocalJson("Guide", this.progressText, this.progress),
      Cfg.initLocalJson("UnlockSystem", this.progressText, this.progress),
      Cfg.initLocalJson("Task", this.progressText, this.progress),
      Cfg.initLocalJson("Event", this.progressText, this.progress),
      Cfg.initLocalJson("Ecological", this.progressText, this.progress),
      Cfg.initLocalJson("Shield", this.progressText, this.progress),
      Cfg.initLocalJson("Bullet", this.progressText, this.progress),
      Cfg.initLocalJson("NickName", this.progressText, this.progress),
      Cfg.initLocalJson("RoleLevel", this.progressText, this.progress),
      Cfg.initLocalJson("Sign", this.progressText, this.progress),
      Cfg.initLocalJson("SkillPool", this.progressText, this.progress),
    ]); //等待所有数据返回
    this.showDebug();
    // 配置表里面的每日抽取次数
    // Cfg.Store.get(1).frequency = 1;
    //在启动模块
    new ModuleLauncher();
    // 启动SDK
    new SdkLauncher(this.progressText, this.progress);
  }

  showDebug() {}
}
